package com.bdqn.t330.controller;


import com.bdqn.t330.common.DtoUtil;
import com.bdqn.t330.entity.Dto;
import com.bdqn.t330.entity.User;
import com.bdqn.t330.service.UserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.cert.TrustAnchor;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(value = "登录接口",tags = {"登录接口123"})
@Controller
@RequestMapping("/login")
public class LoginController {

    private final static Logger log = LoggerFactory.getLogger(LoginController.class);

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    UserService userService;

    /**
     * 登录
     *
     * @param map
     * @return
     */
    @PostMapping("/dologin")
    @ResponseBody
    @CrossOrigin
    public Object doLogin(@RequestBody Map map) {
        String username = (String) map.get("usrName");
        String password = (String) map.get("usrPassword");
        User user = userService.selectOneUserNameBiz(username.trim());
        if (user == null) {
            return DtoUtil.returnFail("用户名不存在", "-1");
        } else if (!user.getUsrPassword().equals(password)) {
            return DtoUtil.returnFail("密码错误", "-2");
        } else {
            String uuid = UUID.randomUUID().toString();
            log.info("uuid:" + uuid);
            try {
                stringRedisTemplate.opsForValue().set(uuid, username, 600, TimeUnit.SECONDS);
                return DtoUtil.returnSuccess("登录成功", user, uuid);
            } catch (Exception e) {
                return DtoUtil.returnSuccess("异常登录", "-1");
            }
        }
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @GetMapping(value = "/logout")
    @ResponseBody
    @CrossOrigin
    public Object logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        Boolean bool = stringRedisTemplate.delete(token);
        return DtoUtil.returnSuccess("退出", bool);
    }
}
